from typing import Dict, Any, Optional, List
from app.services.dify_client import DifyClient
from app.core.logger import logger
from app.models.conversation import ConversationMeta, ConversationCreateRequest, ConversationCreateResponse, ConversationQueryParams, ConversationListResponse, ConversationDeleteResponse, ConversationRenameRequest, ConversationItem, ConversationMessageListResponse

class ConversationService:
    """
    会话服务类
    
    处理会话管理功能，包括创建、获取、更新和删除会话
    """
    def __init__(self, api_key: Optional[str] = None):
        """
        初始化会话服务
        
        Args:
            api_key: 可选的API密钥，如果不提供则使用环境变量中的配置
        """
        self.client = DifyClient(api_key=api_key)
    
    async def create_conversation(
        self, 
        user: str, 
        auto_create: bool = True, 
        conversation_id: Optional[str] = None, 
        meta: Optional[ConversationMeta] = None
    ) -> ConversationCreateResponse:
        """
        创建新会话
        
        Args:
            user: 用户ID
            auto_create: 是否自动创建会话
            conversation_id: 会话ID（当auto_create为False时必须提供）
            meta: 会话元数据
            
        Returns:
            创建结果，包含会话ID
        """
        # 创建请求模型
        request = ConversationCreateRequest(
            user=user,
            auto_create=auto_create,
            conversation_id=conversation_id,
            meta=meta
        )
        
        data = request.dict(exclude_none=True)
        
        logger.debug(f"创建会话: user={user}, auto_create={auto_create}")
        response = await self.client.request(
            method="POST", 
            endpoint="/conversations", 
            data=data
        )
        
        # 返回响应数据
        return response
    
    async def get_conversations(
        self, 
        user: str, 
        limit: int = 20, 
        last_id: Optional[str] = None,
        sort_by: Optional[str] = "-updated_at"
    ) -> ConversationListResponse:
        """
        获取会话列表
        
        Args:
            user: 用户ID
            limit: 每页数量限制，默认20条
            last_id: 当前页最后面一条记录的ID
            sort_by: 排序字段，默认-updated_at(按更新时间倒序排列)
            
        Returns:
            会话列表数据
        """
        # 创建查询参数模型
        query_params = ConversationQueryParams(
            user=user,
            limit=limit,
            last_id=last_id,
            sort_by=sort_by
        )
        
        params = query_params.dict(exclude_none=True)
        
        logger.debug(f"获取会话列表: {params}")
        response = await self.client.request(
            method="GET", 
            endpoint="/conversations", 
            params=params
        )
        
        # 处理并返回响应数据
        return response
    
    async def get_conversation(self, conversation_id: str, user: str) -> ConversationItem:
        """
        获取会话详情
        
        Args:
            conversation_id: 会话ID
            user: 用户ID
            
        Returns:
            会话详情数据
        """
        params = {"user": user}
        
        logger.debug(f"获取会话详情: conversation_id={conversation_id}, user={user}")
        return await self.client.request(
            method="GET", 
            endpoint=f"/conversations/{conversation_id}", 
            params=params
        )
    
    async def update_conversation(
        self, 
        conversation_id: str, 
        user: str, 
        name: Optional[str] = None, 
        meta: Optional[ConversationMeta] = None
    ) -> ConversationItem:
        """
        更新会话
        
        Args:
            conversation_id: 会话ID
            user: 用户ID
            name: 会话名称
            meta: 会话元数据
            
        Returns:
            更新结果
        """
        data = {"user": user}
        
        if name:
            data["name"] = name
            
        if meta:
            data["meta"] = meta.dict(exclude_none=True)
            
        logger.debug(f"更新会话: conversation_id={conversation_id}, user={user}")
        return await self.client.request(
            method="PATCH", 
            endpoint=f"/conversations/{conversation_id}", 
            data=data
        )
    
    async def delete_conversation(self, conversation_id: str, user: str) -> ConversationDeleteResponse:
        """
        删除会话
        
        Args:
            conversation_id: 会话ID
            user: 用户ID
            
        Returns:
            ConversationDeleteResponse: 包含result字段，固定返回"success"
        """
        data = {"user": user}
        
        logger.debug(f"删除会话: conversation_id={conversation_id}, user={user}")
        response = await self.client.request(
            method="DELETE", 
            endpoint=f"/conversations/{conversation_id}", 
            data=data
        )
        
        # 处理响应，确保返回格式正确
        return response
    
    async def get_conversation_messages(
        self, 
        conversation_id: Optional[str], 
        user: str, 
        limit: int = 20, 
        first_id: Optional[str] = None,
        last_id: Optional[str] = None
    ) -> ConversationMessageListResponse:
        """
        获取会话消息
        
        Args:
            conversation_id: 会话ID，可选
            user: 用户ID
            limit: 每页数量限制
            first_id: 第一个消息ID
            last_id: 最后一个消息ID（注意：Dify API不支持此参数，会被忽略）
            
        Returns:
            ConversationMessageListResponse: 会话消息列表
        """
        params = {
            "user": user,
            "limit": limit
        }
        
        # 只有当conversation_id有值时才添加到参数中
        if conversation_id:
            params["conversation_id"] = conversation_id
        
        # 仅当first_id有有效值（不是None、空字符串或"null"字符串）时才添加到参数中
        if first_id and first_id.strip() and first_id.lower() != "null":
            params["first_id"] = first_id
            
        logger.debug(f"获取会话消息: conversation_id={conversation_id}, user={user}, limit={limit}, first_id={first_id}")
        return await self.client.request(
            method="GET", 
            endpoint="/messages", 
            params=params
        )
    
    async def rename_conversation(
        self,
        conversation_id: str,
        user: str,
        name: Optional[str] = None,
        auto_generate: bool = False
    ) -> ConversationItem:
        """
        会话重命名
        
        Args:
            conversation_id: 会话ID
            user: 用户ID
            name: 会话名称（当auto_generate为False时需要提供）
            auto_generate: 是否自动生成标题，默认False
            
        Returns:
            ConversationItem: 更新后的会话信息
        """
        # 创建请求模型
        request = ConversationRenameRequest(
            user=user,
            name=name,
            auto_generate=auto_generate
        )
        
        data = request.dict(exclude_none=True)
        
        logger.debug(f"会话重命名: conversation_id={conversation_id}, user={user}, auto_generate={auto_generate}")
        response = await self.client.request(
            method="POST",
            endpoint=f"/conversations/{conversation_id}/name",
            data=data
        )
        
        return response
